﻿
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using NetCore.Code.Model;
using NetCore.ORM;

namespace NetCore.Code.BLL
{
    /// <summary>
    /// 数据常用模板实例
    /// </summary>
    public class DbTemplateService : SerivceBase, IDbTemplateService
    {
        #region 基本方法
        public static string RootPath
        {
            get {
                return ApplicationEnvironments.BaseDirectory + ApplicationEnvironments.Site.ConfigFile.configPath+ "code/";
            }
        }
        /// <summary>
        /// 查询所有
        /// </summary>
        public List<DbTemplateEntity> GetAll()
        {
            ICriterion criter = Expression.Eq(DbTemplateEntity.__IsDeleted, false);
            return this.Query<DbTemplateEntity>(criter).ToList();
        }
        /// <summary>
        /// 获取单个实例的方法
        /// <param name="id">object类型</param>
        /// </summary>
        public DbTemplateEntity GetById(string id)
        {
            var entity= this.GetById<DbTemplateEntity>(id);
            if (entity != null)
            {
             
                string path = RootPath+ entity.Path + entity.TemplateName + ".tt";
                entity.DataTContent = FileHelper.ReadLine(path.ToLower());
            }
            return entity;

        }

        /// <summary>
        /// 保存方法
        /// <param name="entity">对象</param>
        /// <param name="strError">错误信息</param>
        /// </summary>
        public bool Save(DbTemplateEntity entity, ref string strError)
        {
            if (Exist(entity.TemplateName, entity.ParentId, entity.TemplateId))
            {
                strError = entity.TemplateName + "已存在，请不要重复输入";
                return false;
            }
            if (string.IsNullOrWhiteSpace(entity.TemplateId))
            {
                entity.TemplateId = MyGenerateHelper.GenerateOrder();
            }
            string path = RootPath;
            entity.Path = entity.TemplateName +"/";
            if (!string.IsNullOrWhiteSpace(entity.ParentId))
            {
                var parent = this.GetById<DbTemplateEntity>(entity.ParentId);
                if (parent != null)
                {
                    entity.Path = parent.Path + entity.TemplateName + "/";
                    path += entity.Path ;
                }
                path += entity.TemplateName + ".tt";
                FileInfo fileInfo = new FileInfo(path.ToLower());
                if (!fileInfo.Exists)
                {
                    if (!fileInfo.Directory.Exists)
                    {
                        fileInfo.Directory.Create();
                    }
                }
                else
                {
                    fileInfo.Delete();
                }
                if (!string.IsNullOrWhiteSpace(entity.DataTContent))
                {
                    FileHelper.WriteLine(path, entity.DataTContent);
                }
              
            }
            // entity.OrgId = new NetCore.BLL.SerialRuleService().CreateSerialNo(Organizations_Identity_Num, null, ref strError);// 主键生成值
            return this.SaveOrUpdate<DbTemplateEntity>(entity);

        }
        /// <summary>
        /// 删除方法
        /// <param name="deleteKey">主键，如果字符串请将字符串列表用单引号将字符串用上,如（'aaa','bbb'）</param>
        /// <param name="strError">错误信息</param>
        /// </summary>
        public bool Delete(string deleteKey, ref string strError)
        {
            if (!string.IsNullOrEmpty(deleteKey))
            {
               var result= this.Query<DbTemplateEntity>(Expression.In(DbTemplateEntity.__ParentId, deleteKey.Split(new char[] { ';', ',' })));
                if (result != null && result.Count > 0)
                {
                    strError = "该模板下还有其它子模版，无法删除！";
                    return false;
                }
                return this.Delete<DbTemplateEntity>(deleteKey);
            }
            return true;
        }
        /// <summary>
        /// 分页查询方法
        /// <param name="grid">分页查询的相关参数</param>
        /// </summary>
        public LigerGrid ForGrid(LigerGrid ligerGrid)
        {
            ICriterion criter = Expression.Eq("IsDeleted", false);
            if (!string.IsNullOrEmpty(ligerGrid.keyWord))
            {
                criter = Expression.And(criter,

                           Expression.Like(new string[] {
                                DbTemplateEntity._PrimaryKeyName ,
                                DbTemplateEntity.__TemplateName
                           }, ligerGrid.keyWord)
                           );
            }
            return this.Query<DbTemplateEntity>(ligerGrid, criter);

        }
        #endregion

        #region 扩展方法
        /// <summary>
        /// 验证是否存在的方法
        /// <param name="name">需要验证的值</param>
        /// <param name="key">主键</param>
        /// </summary>
        public bool Exist(string name,string parentid, string key)
        {
            key = (string.IsNullOrWhiteSpace(key)) ? "" : key;

            ICriterion criter = Expression.Eq("IsDeleted", false);
            criter =
                Expression.And(criter, Expression.And(Expression.Eq(DbTemplateEntity.__TemplateName, name),
                Expression.Not(Expression.Eq(DbTemplateEntity._PrimaryKeyName, key)))
                );
            if (string.IsNullOrWhiteSpace(parentid))
            {
                criter = Expression.And(criter, Expression.IsNull(DbTemplateEntity.__ParentId));
            }
            else
            {
                criter = Expression.And(criter, Expression.Eq(DbTemplateEntity.__ParentId,parentid));
            }
            var result = this.Query<DbTemplateEntity>(criter).FirstOrDefault();
            return result != null;
        }

        public List<DbTemplateEntity> GetChildren(string parentid)
        {
            ICriterion criter = Expression.Eq(DbTemplateEntity.__IsDeleted, false);
            if (string.IsNullOrWhiteSpace(parentid))
            {
                criter = Expression.And(criter, Expression.IsNull(DbTemplateEntity.__ParentId));
            }
            else
            {
                criter = Expression.And(criter, Expression.Eq(DbTemplateEntity.__ParentId,parentid));
            }
            return this.Query<DbTemplateEntity>(criter).ToList();
        }
        #endregion

        #region 事件

        #endregion
    }
}